import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';

declare var $:any;
@Component({
  selector: 'app-date-selector',
  templateUrl: './date-selector.component.html'
})
export class DateSelectorComponent implements OnInit {
  @Input() public yearShow:boolean = true;
  @Input() public monthShow:boolean = true;
  @Input() public dayShow:boolean = true;
  @Output() public date:EventEmitter<any> = new EventEmitter<any>();

  year:any = 0;
  yearData = [];
  month:any = 0;
  monthData = [1,2,3,4,5,6,7,8,9,10,11,12];
  day:any = 0;
  dayData = [];

  constructor() {
    this.initCurrentDate();
    this.date.emit({year:this.year,month:this.month,day:this.day});
  }

  ngOnInit() {

  }

  initCurrentDate(){
    let date = new Date();
    this.year = date.getFullYear();
    this.month = date.getMonth() + 1;
    this.day = date.getDate();
    for(let i = 2016 ; i <= this.year + 3 ; i++){
      this.yearData.push(i);
    }
    this.getDayData();

   // console.log(this.yearData)
  }

  getMonthData(){
    this.monthData = [];
    if(this.year == 0) return;
    for(let i = 1 ; i <= 12 ; i++){
      this.monthData.push(i);
    }
  }
  getDayData(){
    this.dayData = [];
    if(this.month == 0) return;
    let days = new Date(this.year,this.month,0).getDate();
    for(let i = 1 ; i <= days ; i++){
      this.dayData.push(i);
    }
  }

  onChange(type){
    switch (type){
      case 'year':
        this.month = 0;
        this.getMonthData();
      case 'month':
        this.day = 0;
        this.getDayData();
    }

    this.date.emit(this.date2Object());
  }

  date2Object():any{
    let date$ = {year:this.year,month:this.month,day:this.day,time:'',type:''};
    if(date$.year == 0){
      date$.time = this.yearData[0] +　'-1-1';
      date$.type = 'year';
    }
    if(date$.year != 0 && date$.month ==0){
      date$.time = date$.year + '-1-1';
      date$.type = 'month';
    }

    if(date$.month !=0 && date$.day == 0){
      date$.time = date$.year + '-' + date$.month　+ '-1';
      date$.type = 'day';
    }

    if(date$.day != 0){
      date$.time = date$.year + '-' + date$.month　+ '-' + date$.year;
      date$.type = 'hour';
    }

    return date$;
  }
}
